<template>
  <Header title="记录审查" sub="让我康康是谁借了啥"/>
  <el-table :data="tableData">
    <el-table-column label="姓名" prop="name"/>
    <el-table-column label="原因" prop="reason_name"/>
    <el-table-column prop="state" label="处理状态">
      <template #default="scope">
        <el-tag :type="getTag(scope.row.state)">{{ scope.row.state }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="查看详情">
      <template #default="scope">
        <el-button size="small" @click="detailEdit(scope.$index, scope.row)" type="primary" round>详情</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog v-model="editDialog" fullscreen title="编辑借用记录" :show-close="false">
    <el-form :model="editing" label-width="auto">
      <el-form-item label="姓名：">
        <el-input v-model="editing.name"  disabled/>
      </el-form-item>
      <el-form-item label="工/学号：">
        <el-input v-model="editing.identity" disabled/>
      </el-form-item>
      <el-form-item label="手机号码：">
        <el-input v-model="editing.phone_number" disabled/>
      </el-form-item>
      <el-form-item label="借用事项：">
        <el-select v-model="editing.reason_type" style="width: 100%" disabled>
          <el-option value="教信系教师课程及科研实践项目"></el-option>
          <el-option value="教信系学生课外学术科研项目"></el-option>
          <el-option value="教信系学生个人自立项目"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目名：">
        <el-input v-model="editing.reason_name" disabled/>
      </el-form-item>
      <el-form-item label="取用时间：">
        <el-date-picker
            v-model="editing.receive_time"
            type="datetime"
            placeholder="Select date and time"
            style="width: 100%"
            format="YYYY-MM-DD hh:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            disabled
        />
      </el-form-item>
      <el-form-item label="实际取用时间：">
        <el-date-picker
            v-model="editing.actual_receive_time"
            type="datetime"
            placeholder="Select date and time"
            style="width: 100%"
            format="YYYY-MM-DD hh:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="actual_receive_time_changed = true"
        />
      </el-form-item>
      <el-form-item label="归还时间：">
        <el-date-picker
            v-model="editing.return_time"
            type="datetime"
            placeholder="Select date and time"
            style="width: 100%"
            format="YYYY-MM-DD hh:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            disabled
        />
      </el-form-item>
      <el-form-item label="实际归还时间：">
        <el-date-picker
            v-model="editing.actual_return_time"
            type="datetime"
            placeholder="Select date and time"
            style="width: 100%"
            format="YYYY-MM-DD hh:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="actual_return_time_changed = true"
        />
      </el-form-item>
      <el-form-item label="备注：">
        <el-input v-model="editing.note" @change="note_changed = true"/>
      </el-form-item>
      <el-form-item label="处理后状态：">
        <el-select v-model="editing.state" style="width: 100%">
          <el-option value="未处理" :disabled="real_state !== '未处理'"></el-option>
          <el-option value="待取" :disabled="real_state !== '未处理' && real_state !== '待取'"></el-option>
          <el-option value="借出" :disabled="real_state !== '未处理' && real_state !== '待取' && real_state !== '借出'"></el-option>
          <el-option value="部分还回" :disabled="real_state === '归还'"/>
          <el-option value="归还" :disabled="real_state !== '借出' && real_state !== '部分还回'"/>
          <el-option value="驳回" :disabled="real_state !== '未处理'"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="处理人：">
        <el-input v-model="editing.lenter" @change="lenter_changed = true"/>
      </el-form-item>
    </el-form>
    <el-tabs v-model="activeName" stretch type="card">
      <el-tab-pane v-for="(obj, keyName) in all_device" :key="keyName" :label="keyName">
        <DeviceForm :name="keyName" :device_json="obj" :without_disable="editing['state'].indexOf('还') !== -1" :device_selected="editing['state'].indexOf('还') === -1 ? editing['device'] : editing['return_device']"/>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="danger" @click="cancel">不提交</el-button>
        <el-button @click="confirm" type="success">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import Header from "@/components/Header";
import DeviceForm from "@/components/Approve_DeviceForm";
import axios from "axios";
import {ElNotification} from "element-plus";

const successNotification = () => {
  ElNotification({
    title: '提交成功！',
    message: '请刷新页面查看最新状态',
    type: 'success',
  })
}

const failureNotification = (msg = '请刷新页面重新提交，或直接联系工作室成员') => {
  ElNotification({
    title: '提交失败',
    message: msg,
    type: 'error',
    duration: 0,
  })
}

const categories = ['相机类', '镜头类', '电池类', '存储类', '转接类', '常用配件类', '不常用配件类'];

export default {
  name: "Approve_Main",
  data() {
    return {
      'tableData': [],
      'haveNext': true,
      'page': 0,
      'tableClass': [],
      'editDialog': false,
      'editing': Object(),
      'activeName': "0",
      all_device: Object(),
      actual_receive_time_changed: false,
      actual_return_time_changed: false,
      note_changed: false,
      lenter_changed: false,
      real_state: '',
    }
  },
  created() {
    document.title = "记录审查"
    window.addEventListener('scroll', this.scrollHandle, true)
    window.localStorage.removeItem("Approve")
    this.refresh()
    for(const key of categories) {
      axios.get("/api/getByCategory", {params: {
          'permission': 1,
          'category': key,
        }}).then(res => {
        if(res.status === 200) {
          this.all_device[key] = res.data
        }else {
          console.log(res);
        }
      }).catch(e => {
        console.log(e);
      })
    }
  },
  methods: {
    scrollHandle() {
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      //变量windowHeight是可视区的高度
      let windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
      //变量scrollHeight是滚动条的总高度
      let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
      //滚动条到底部的条件
      if (scrollTop + windowHeight >= scrollHeight - 200 && this.isRefreshBool) {
        // false防止refresh()加载数据函数多次触发
        this.isRefreshBool = false;
        this.refresh();
      }

    },
    refresh() {
      axios.get("/api/record", {
        params: {
          'page': this.page
        }
      }).then(res => {
        if (res.status !== 200) {
          console.log(res);
          return;
        }
        let result = res.data;
        this.tableData = this.tableData.concat(result['records'])
        if(!result['haveNext']) {
          this.isRefreshBool = false;
          window.removeEventListener('scroll', this.scrollHandle, false)
          return;
        }
        this.page++;
        this.isRefreshBool = true;
      }).catch(e => {
        console.log(e);
      })
    },
    getTag(state) {
      switch (state) {
        case '未处理':
          return 'warning'
        case '借出':
          return 'danger'
        case '部分还回':
          return 'danger'
        case '归还':
          return 'success'
        case '驳回':
          return 'info'
        case '待取':
          return ''
      }
    },
    detailEdit(index, row) {
      this.editing = Object.assign({}, row);
      this.real_state = row.state
      this.editDialog = true
    },
    confirm() {
      let data_sent = Object();
      data_sent['id'] = this.editing.id;
      data_sent['state'] = this.editing.state;
      if(this.actual_receive_time_changed)
        data_sent['actual_receive_time'] = this.editing.actual_receive_time
      if(this.actual_return_time_changed)
        data_sent['actual_return_time'] = this.editing.actual_return_time
      if(this.note_changed)
        data_sent['note'] = this.editing.note
      if(this.lenter_changed)
        data_sent['lenter'] = this.editing.lenter
      if(window.localStorage["Approve"]) {
        let device_category = JSON.parse(window.localStorage["Approve"])
        data_sent['device'] = {}
        for(const category in device_category) {
          data_sent['device'][category] = {}
          for(const name in device_category[category]) {
            data_sent['device'][category][name] = []
            for(const num of device_category[category][name]) {
              let number = num.substr(0, 2);
              data_sent['device'][category][name].push(parseInt(number));
            }
          }
        }
      }
      axios.post('/api/record_update', data_sent).then(res => {
        if(res.status === 200) {
          successNotification()
        }else {
          failureNotification("请刷新页面重新提交，或联系社长")
        }
      }).catch(e => {
        failureNotification("请刷新页面重新提交，或将下列信息复制发给社长" + e.response.data)
      })
      this.editDialog = false
    },
    cancel() {
      this.editDialog = false
    }
  },
  components: {
    Header,
    DeviceForm,
  },
}
</script>

<style scoped>
.dialog-footer button:first-child {
  margin-bottom: 10px;
}
</style>